package com.sdp.irrigation.server.netty.response;

import java.util.Map;
import java.util.Set;

import com.sdp.irrigation.server.netty.channel.IChannelManager;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonResponseHandle implements IResponseHandle {

	private IChannelManager channelService;
	
	public JsonResponseHandle(IChannelManager channelService) {
		this.channelService = channelService;
	}
	
	@Override
	public void sendMessage(String devSn, Object message) {
		if (message != null) {
			Set<Channel> channelSet = channelService.get(devSn);
			if (channelSet.size() > 0) {
				for (Channel channel : channelSet) {
					if (channel.isActive()) {
						channel.writeAndFlush(message).addListener(new ChannelFutureListener(){

							@Override
							public void operationComplete(ChannelFuture future) throws Exception {
								// TODO Auto-generated method stub
								if (future.isSuccess()) {
									
								} else {
									if (future.cause() != null) {
										log.error("消息发送失败，错误信息为：[{}]", future.cause().getMessage());
					                	StackTraceElement[] stacks = future.cause().getStackTrace();
					                	for (StackTraceElement stackTraceElement : stacks) {
					                		log.error(stackTraceElement.toString());
										}
									}
								}
							}
							
						});
					} else {
						log.error("devSn: [{}] 对应的设备通道不可用", devSn);
					}
				}
			} else {
				log.error("devSn: [{}] 对应的设备通道不存在", devSn);
			}
			
		}
		
//		ChannelSession session = channelService.getSession(devSn);
//		Channel channel = channelService.get(devSn);
//		if (session != null && channel != null && channel.isActive() && message != null) {
//			channel.writeAndFlush(message).addListener(new ChannelFutureListener(){
//
//				@Override
//				public void operationComplete(ChannelFuture future) throws Exception {
//					
//					if (future.isSuccess()) {
//						
//					} else {
//						if (future.cause() != null) {
//							log.error("消息发送失败，错误信息为：[{}]", future.cause().getMessage());
//		                	StackTraceElement[] stacks = future.cause().getStackTrace();
//		                	for (StackTraceElement stackTraceElement : stacks) {
//		                		log.error(stackTraceElement.toString());
//							}
//						}
//					}
//				}
//				
//			});
//		} else {
//			log.error("devSn: [{}] 对应的设备通道不存在", devSn);
//		}
	}

	@Override
	public Map<String, Map<String, ChannelId>> getChannelIdMap() {
		return channelService.getChannelIdMap();
	}

}
